/*  Copyright 2010 princehaku
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Author     : princehaku
 */
package net.techest.httpproxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.Socket;
import java.net.URL;
import java.text.ParseException;
import java.util.StringTokenizer;

import net.techest.httpprotocols.HTTPRequest;
import net.techest.httpprotocols.HTTPRequestBuilder;

public class HTTPThread extends Thread {

	Socket client;

	InputStream in;

	OutputStream out;

	// Keep track of the client socket
	public HTTPThread(Socket client) {
		this.client = client;
	}

	@Override
	public void run() {

		try {
			this.client.setSoTimeout(600);
			in = this.client.getInputStream();
			HTTPRequest request = null;
			try {
				request=HTTPRequestBuilder.buildRequest(in);
			} catch (ParseException e) {
				throw new Exception(e);
			}
			request.setParam("Accept-Encoding", "plain");
			request.setParam("Proxy-Connection", null);
			
			StringTokenizer st = new StringTokenizer(request.getStatuLine(), " ");
			String requestType=st.nextToken();
			String url=st.nextToken();
			String protocols=st.nextToken();
			URL turl=new URL(url);
			System.out.println("解析到HOST字段"+turl.getHost());
			
			int port=turl.getPort();
			if(port==-1)port=80;
			Socket sck = new Socket(turl.getHost(), port);
			request.setStatuLine(requestType+" "+turl.getPath()+" HTTP/1.0");
			
			sck.getOutputStream().write(request.toString().getBytes());
			sck.getOutputStream().write("\n\n".getBytes());

			sck.setSoTimeout(1500);
			pipe(sck.getInputStream(), this.client.getOutputStream());
			this.client.getOutputStream().close();

		} catch (Exception e) {
			System.out.println("进程终止"+e.getMessage());
		}
		try {
			this.client.close();
		} catch (IOException e1) {
			System.out.println("关闭socket失败"+e1.getMessage());
		}
	}

	public void pipe(InputStream is0, OutputStream os0) {
		System.out.println("转发数据");
		int ir = 1;
		byte bytes[] = new byte[1024];
			try {
				while (ir > 0) {
				//System.out.println("等待读入");
				if ((ir = is0.read(bytes)) > 0) {
					os0.write(bytes, 0, ir);
				} else if (ir < 0)
					break;
				}
			} catch (Exception e0) {
				System.out.println("Pipe异常: " + e0);
			}
		System.out.println("转发完毕");
	}
}
